package cn.ecnu.comment.interceptor;

import cn.ecnu.common.Constant;
import cn.ecnu.common.Permission;
import cn.ecnu.exception.RRXException;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler; // 处理这个请求的函数
        Method method = handlerMethod.getMethod();

        if (method.isAnnotationPresent(Own.class)) { // 获取方法上的注解
//            int userId = Integer.parseInt(request.getHeader("userId")); // 获取ID
            String permission = request.getHeader("permission"); // 获取权限字段
            if (permission == null) throw new RRXException(Constant.PERMISSION_ERROR.getMsg(), Constant.PERMISSION_ERROR.getCode());

            Own own = method.getAnnotation(Own.class);
            if (own != null && !Permission.hasPermission(permission, own.permission()))
                throw new RRXException(Constant.NO_PERMISSION.getMsg(), Constant.NO_PERMISSION.getCode());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
